package com.sh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sh.common.BaseResult;
import com.sh.common.enums.BizCodeEnum;
import com.sh.common.pojo.Contants;
import com.sh.common.pojo.bo.PutObjectRes;
import com.sh.common.utils.FileUtil;
import com.sh.entity.FileResource;
import com.sh.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;


@Slf4j
@RestController
@RequestMapping("/operator")
public class FileResourceController {

    @Autowired
    private IOSSService ossService;

    @Autowired
    private IFileResourceService fileResourceService;


    @PostMapping("/upload")
    public BaseResult upload(@RequestParam("file")MultipartFile file) throws IOException {
        String hashCode = FileUtil.calFileFingerPrint(file.getInputStream(), FileUtil.ALGORITHM_MD5);
        QueryWrapper<FileResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hash_code", hashCode);
        FileResource fileResource = fileResourceService.getOne(queryWrapper);
        if (fileResource != null) {
            return BaseResult.success(PutObjectRes.builder()
                    .key(fileResource.getFileUrl())
                    .fileResourceId(fileResource.getId())
                    .build());
        }
        String filename = file.getOriginalFilename();
        String newFileName = filename.substring(0, filename.lastIndexOf(".")) + "_"  +
                hashCode + filename.substring(filename.lastIndexOf("."));
        String key = FileUtil.generateFileOssKey(newFileName);
        PutObjectRes uploadRet = ossService.putObject(key, file);
        if (uploadRet.getSuccess()) {
            String url = Contants.OSS_PREFIX + key;
            fileResource = new FileResource();
            fileResource.setFileName(file.getOriginalFilename());
            fileResource.setFileSize(file.getSize());
            fileResource.setFileUrl(url);
            fileResource.setContentType(file.getContentType());
            fileResource.setHashCode(hashCode);
            fileResource.setEtag(uploadRet.getEtag());
            fileResourceService.save(fileResource);

            uploadRet.setFileResourceId(fileResource.getId());
            uploadRet.setKey(url);
            return BaseResult.success(uploadRet);
        } else {
            return BaseResult.fail(BizCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

}
